package Design_patterns.creator_mode.singleton.demo8;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @description: 测试使用反射破坏单例模式
 **/

public class Client {
    public static void main(String[] args) {
        //1.获取Singleton字节码对象
        Class<Singleton> clazz = Singleton.class;
        try {
            //2.获取无参构造方法对象
            Constructor<Singleton> cons = clazz.getDeclaredConstructor();

            //3.取消访问检查
            cons.setAccessible(true);

            //4.创建singleton对象
            Singleton singleton = cons.newInstance();
            Singleton singleton2 = cons.newInstance();

            // 如果true就是没破坏单例模式
            System.out.println(singleton == singleton2);
            //结果： false   破坏了单例模式

        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
